package com.gzk.basic.service.impl;

import com.gzk.basic.constant.BaseConstant;
import com.gzk.basic.exception.BusinessException;
import com.gzk.basic.service.IVerifyService;
import com.gzk.basic.util.StrUtils;
import com.gzk.user.domain.User;
import com.gzk.user.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyServiceImpl implements IVerifyService {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void phoneCode(Map<String,String> map) {
        String phone = map.get("phone");
        String type = map.get("type");
        //判断手机号是否为空
        if(phone == null){
            throw new BusinessException("手机号不能为空！！");
        }

        //判断是注册还是绑定
        String prefix = "";
        if("register".equals(type)){
            //如果手机号不为空，查询是否已经被注册
            User user = userService.loadByPhone(phone);
            //判断用户是否存在
            if(user != null){
                throw new BusinessException("手机号已经被注册，请直接登录！");
            }
            //注册
            prefix = BaseConstant.BUSINESS_REGISTER_PREFIX;
        }else if ("binder".equals(type)){
            prefix = BaseConstant.BUSINESS_BINDER_PREFIX;
        }

        sendPhoneCode(prefix, phone);

    }

    @Override
    public void emailCode(String email) {
        //判断手机号是否为空
        if(email == null){
            throw new BusinessException("邮箱不能为空！！");
        }
        //如果手机号不为空，查询是否已经被注册
        User user = userService.loadByEmail(email);
        //判断用户是否存在
        if(user != null){
            throw new BusinessException("邮箱已经被注册，请直接登录！");
        }
        //用户不存在
        //取redis中的信息
        String val = (String)redisTemplate.opsForValue().get(BaseConstant.BUSINESS_REGISTER_PREFIX + email);

        String code = "";
        //判断val是否为空
        if(val != null){
            //没到过期时间
            //判断是否过了一分钟
            String startTime = val.split(":")[1];
            if ((System.currentTimeMillis() - Long.valueOf(startTime)) <= 60*1000){
                //一分钟之内，直接报错
                throw new BusinessException("你要爪子!");
            }
            //过了一分钟没过五分钟，使用原来的验证码发送回去，并且重新设置生命周期
            code = val.split(":")[0];
        }else {
            //val为空(第一次请求验证码或者验证码过期都要重新发送验证码，并且设置生命周期为三分钟)
            //获取验证码
            code = StrUtils.getComplexRandomString(4);
        }

        String codeval = code +":"+System.currentTimeMillis();
        redisTemplate.opsForValue().set(BaseConstant.BUSINESS_REGISTER_PREFIX+email,
                codeval,
                5,
                TimeUnit.MINUTES);

        //发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("694754772@qq.com");
        message.setTo(email);
        message.setSubject("欢迎注册宠物乐园平台！");
        message.setText("<h3>您的验证码：</h3>"+code+"<br/><h4>请在五分钟之内使用</h4>");
        javaMailSender.send(message);
        System.out.println("<h3>您的验证码：</h3>"+code);
    }

    /**
     * 发送手机验证码
     */
    private void sendPhoneCode(String prefix,String phone){
        //取redis中的信息
        String val = (String)redisTemplate.opsForValue().get(prefix + phone);

        String code = "";
        //判断val是否为空
        if(val != null){
            //没到过期时间
            //判断是否过了一分钟
            String startTime = val.split(":")[1];
            if ((System.currentTimeMillis() - Long.valueOf(startTime)) <= 60*1000){
                //一分钟之内，直接报错
                throw new BusinessException("兄弟别搞事!");
            }
            //过了一分钟没过三分钟，使用原来的验证码发送回去，并且重新设置生命周期
            code = val.split(":")[0];
        }else {
            //val为空(第一次请求验证码或者验证码过期都要重新发送验证码，并且设置生命周期为三分钟)
            //获取验证码
            code = StrUtils.getComplexRandomString(4);
        }

        String codeval = code +":"+System.currentTimeMillis();
        redisTemplate.opsForValue().set(prefix+phone,
                codeval,
                3,
                TimeUnit.MINUTES);
        System.out.println("你的验证码是:"+code +"请在三分钟内使用");
    }
}
